var logger = require('../../lib/logger.lib');
var sha1 = require('../services/sha1.service');
var usersService = require('../services/users.service');
var pagesService = require('../services/pages.service');//查询单页信息渲染
var siteInfoService = require('../services/site-info.service');
var categoriesService = require('../services/categories.service');
var async = require('async');
var md5 = require("md5");
var https = require("https");
var moment = require("moment");

// var captcha = require('../../lib/captcha.lib');


module.exports = {
	register: function (req, res) {
		logger.system().info('提交注册申请');
		req.checkBody({
			'email': {
				notEmpty: {
					options: [true],
					errorMessage: 'email 不能为空'
				},
				isEmail: { errorMessage: 'email 格式不正确' }
			},
			'nickname': {
				notEmpty: {
					options: [true],
					errorMessage: 'nickname 不能为空'
				},
				isString: { errorMessage: 'nickname 需为字符串' }
			},
			'password': {
				notEmpty: {
					options: [true],
					errorMessage: 'password 不能为空'
				},
				isLength: {
					options: [6],
					errorMessage: 'password 不能小于 6 位'
				}
			},

			'PhoneNumber': {
				optional: true,
				isString: { errorMessage: 'PhoneNumber 格式不正确' }
			},
			'WeiXinID': {
				optional: true,
				isString: { errorMessage: 'WeiXinID 需为字符串' }
			},
			'WorkYears': {
				optional: true,
				isString: { errorMessage: 'WorkYears 需为字符串' }
			},
		});

		if (req.validationErrors()) {
			logger.system().error(__filename, '参数验证失败', req.validationErrors());
			return res.status(400).end();
		}

		var data = {
			type: 'admin',
			email: req.body.email,
			nickname: req.body.nickname,
			password: req.body.password,
			PhoneNumber: req.body.PhoneNumber,
			WeiXinID: req.body.WeiXinID,
			WorkYears: req.body.WorkYears,
			role: '59c0a13b1c92974bf0c0e068'
		};
		//console.log(data)
		usersService.save({ data: data }, function (err, user) {
			if (err) {
				logger[err.type]().error(__filename, err);
				return res.status(500).end();
			}
			logger.system().info('存储' + user);

			///hyfw/hyxx 跳转页面
			//res.status(200).json({ _id: user._id });
			//res.status(200)

			logger.system().info('准备渲染页面');

			pagesService.one({
				path: '/hyfw/hydl'
			}, function (err, page) {
				logger.system().info('进入回调');
				if (err) return res.status(500).end();

				if (!page) return next();
				logger.system().info('开始异步渲染页面');

				// 读取单页所需数据
				async.parallel({
					siteInfo: siteInfoService.get,
					navigation: function (callback) {
						categoriesService.navigation({ current: page.path }, callback);
					}
				}, function (err, results) {
					res.render(page.views.page, {
						layout: page.views.layout,
						siteInfo: results.siteInfo,
						navigation: results.navigation,
						category: page,
						content: page.mixed.pageContent,
						media: page.mixed.pageMedia,
						// user: user
					});
					//res.status(200).json(user)
				});
			});

		});
	},

	// sendVCode: function (req, res) {
	// 	logger.system().info('后台发送验证码');
	// 	var PhoneNumber = req.query.PhoneNumber;
	// 	logger.system().info(PhoneNumber);

	// 	if (PhoneNumber == undefined) {
	// 		logger.system().info('请求失败!' + 手机号为空);
	// 		res.status(500).end()
	// 	}
	// 	var now = moment();
	// 	var timestamp = now.format("YYYYMMDDHHmmss");
	// 	var account = "ba841fb4abe734e4c7993c8c0e9ef19a";
	// 	var token = "41e4b8a727066bd380e70bce3c147fea";
	// 	var appId = "d725caf59d1b4d319cdc7528ced53e58";
	// 	var sig = md5(account + token + timestamp);
	// 	var auth = new Buffer(account + token + timestamp).toString('base64');

	// 	var contents = JSON.stringify({
	// 		"templateSMS": {
	// 			"appId": appId,
	// 			"param": "123456",
	// 			"templateId": "156517",
	// 			"to": PhoneNumber
	// 		}
	// 	});

	// 	logger.system().info("content: " + contents);

	// 	var opt = {
	// 		'host': 'api.ucpaas.com',
	// 		'path': '/2014-06-30/Accounts/ba841fb4abe734e4c7993c8c0e9ef19a/Messages/templateSMS?sig=' + sig,
	// 		'method': 'POST',
	// 		'headers': {
	// 			'Content-Type': 'application/json;charset=utf-8',
	// 			'Content-Length':contents.length,
	// 			'Accept': 'application/json',
	// 			'Authorization': auth
	// 		},
	// 	}

	// 	logger.system().info(opt);

	// 	var req = https.request(opt, function (feedback) {
	// 		logger.system().info(feedback.statusCode + ' ');
	// 		if (feedback.statusCode == 200) {
	// 			logger.system().info('test');
	// 			var post = '';
	// 			feedback.on('data', function (chunk) {
	// 				logger.system().info(post);
	// 				post += chunk;
	// 			})
	// 			.on('end', function () {
	// 				return res.status(200).json(post).end()
	// 			});
	// 		} else {
	// 			logger.system().info('请求失败!' + feedback.statusCode);
	// 			return res.status(500).end();
	// 		}
	// 	})
	// 	req.write(contents);
	// 	req.end;
	// }
	sendVCode: function (req, res) {
		logger.system().info('后台发送验证码');
		var PhoneNumber = req.query.PhoneNumber;
		logger.system().info(PhoneNumber);

		if (PhoneNumber == undefined) {
			logger.system().info('请求失败!' + 手机号为空);
			res.status(500).end()
		}
		var appId = "f5bbac8ac9c0924e009ac27402440d70";
		var nonce = 12342;
		var now = moment().utc();
		var appSecret = "9a32d0b37169";
		var checkSum = sha1(appSecret + nonce + now);
		logger.system().info("checkSum=" + checkSum)
		var params = "123456";
		var templateId = "templateid ";
		var opt = {
			'host': 'api.netease.im',
			'path': '/sms/sendtemplate.action',
			'method': 'POST',
			'headers': {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
				'AppKey': appId,
				'Nonce': nonce,
				'CurTime': now,
				'CheckSum': checkSum
			},
		}

		var contents = JSON.stringify({
			'mobile': PhoneNumber,
			'templateid': templateId
		});

		//logger.system().info(opt);

		var req = https.request(opt, function (feedback) {
			logger.system().info(feedback.statusCode + ' ');
			if (feedback.statusCode == 200) {
				logger.system().info('test');
				//var post = '';
				feedback.on('data', function (chunk) {
					logger.system().info(chunk);
					return res.status(200).json(chunk).end()
					//post += chunk;
				})
				// .on('end', function () {
				// 	return res.status(200).json(post).end()
				// });
			} else {
				logger.system().info('请求失败!' + feedback.statusCode);
				return res.status(500).end();
			}
		})
		req.write(contents).end();
	}
}